﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CollectionUtil.DataStructure.Lists
{
    class ArrayList : List
    {
        object[] elementData;
        int size;

        public ArrayList() 
        {
            elementData = new object[1];
            size = 0;
        }

        public void Add(int i, object e)
        {
            EndsureCapacity(size);
            for (int m = size - 1; m >= i;m-- )
            {
                elementData[m+1] = elementData[m];
            }
            elementData[i] = e;
            size++;
        }

        public void Remove(int i)
        {
            for (int m = i; m < size; m++)
            {
                elementData[m] = elementData[m + 1];
            }
            size--;
        }

        public object Get(int i)
        {
            return elementData[i];
        }

        public void Set(int i, object e)
        {
            elementData[i] = e;
        }

        #region Collection Members

        public void Add(object e)
        {
            Add(size, e);
        }

        public void Remove(object e)
        {
            int index = -1;
            for (int i = 0; i < size; i++)
            {
                if (elementData[i].Equals(e)) 
                {
                    index = i;
                    break; 
                }
            }
            Remove(index);
        }

        public bool Contain(object e)
        {
            throw new NotImplementedException();
        }

        public bool IsEmpty()
        {
            return size == 0;
        }

        public int Size()
        {
            return size;
        }

        #endregion


        private void EndsureCapacity(int c)
        {
            if (c >= elementData.Length)
            {
                object[] newData = new object[elementData.Length * 2];
                for (int i = 0; i < size; i++)
                {
                    newData[i] = elementData[i];
                }
                elementData = newData;
            }
        }

        public override string ToString()
        {
            string ret = "[";
            for (int i = 0; i < size; i++)
            {
                ret += elementData[i]+",";
            }
            return ret+"]";
        }
    }
}
